package pers.liuchengyin.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

/**
 * @ClassName EsConfig
 * @Description
 * @Author 柳成荫
 * @Date 2022/3/27
 */
@Configuration
public class EsConfig {

    @Value("${elasticsearch.cluster-nodes}")
    private String clusterNodes;

    public static final RequestOptions COMMON_OPTIONS;

    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
        COMMON_OPTIONS = builder.build();
    }

    private HttpHost buildHttpHost(String node) {
        String[] nodeInfo = node.split(":");
        return new HttpHost(nodeInfo[0].trim(), Integer.parseInt(nodeInfo[1].trim()), "http");
    }

    @Bean
    public RestHighLevelClient elasticSearchRestClient() {
        String[] nodes = clusterNodes.split(",");
        return new RestHighLevelClient(
                RestClient.builder(
                        Arrays.stream(nodes).map(this::buildHttpHost).toArray(HttpHost[]::new)
                ));
    }

}
